package SqlJavaBean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class StudentW {
	private Connection con;
	public String res;
	
	public StudentW(){
		DBBean db = new DBBean();
		con = db.getConnection();
		res = "";
	}
	public boolean setPartData(String user,String partName,String data){
		String[] re = data.split("\u0001");
		try{
			String sqlx = "update Practise set anserData=?,whenLong=whenLong+? where user=? and practiseID=?";
			PreparedStatement update = con.prepareStatement(sqlx);
			int flag = 0;
			for(String s:re){
				String[] xxx = s.split("\u0002");
				update.setString(1, xxx[1]);
				update.setString(2, xxx[2]);
				update.setString(3, user);
				update.setString(4, xxx[0]);
				flag = update.executeUpdate();
			}
			if(flag>0) return true;
			String sql = "insert into Practise(user,practiseID,anserData,whenLong,partName) values(?,?,?,?,?)";
			PreparedStatement insert = con.prepareStatement(sql);
			for(String s:re){
				String[] xxx = s.split("\u0002");
				insert.setString(1, user);
				insert.setString(2, xxx[0]);
				insert.setString(3, xxx[1]);
				insert.setString(4, xxx[2]);
				insert.setString(5, partName);
				insert.executeUpdate();
			}
		}
		catch(Exception e){
			res = e.getMessage();
			return false;
		}
		return true;
	}
	public boolean setExamData(String user,String data){
		String[] re = data.split("\u0001");
		try{
			String examName = "";
			Statement sta = con.createStatement();
			ResultSet rs = sta.executeQuery("select examName from RecentExam");
			if(rs.next()) examName = rs.getString(1);
			String sql = "insert into Subject(user,subjectID,anserData,examName) values(?,?,?,?)";
			PreparedStatement update = con.prepareStatement(sql);
			for(String s:re){
				String[] xxx = s.split("\u0002");
				update.setString(1, user);
				update.setString(2, xxx[0]);
				update.setString(3, xxx[1]);
				update.setString(4, examName);
				update.executeUpdate();
			}
		}
		catch(Exception e){
			res = e.getMessage();
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
